package com.mrx.java8.optional;

import org.junit.jupiter.api.Test;

import java.util.Optional;

public class TestOptional {
    /**
     * Optional.of(T t) : 创建一个Optional实例
     * Optional.empty() : 创建一个空的Optional实例
     * Optional.ofNullable(T t) : 若t不为null,创建Optional实例，否则创建空实例
     * isPresent(): 判断是否包含值
     * orElse(T l) : 如果调用对象包含值，返回该值，否则返回t
     * orElseGet(Supplier s) : 如果调用对象包含值，返回该值，否则返回s获取的值
     * map(Function f) : 如果有值对其处理，并返回处理后的Optional,否则返回Optional.empty()
     * flatMap(Function mapper) : 与map类似，要求返回值必须是Optional
     */
    @Test
    public void test1(){
        Optional<Employee> op = Optional.of(new Employee());
        Employee e = op.get();
        System.out.println(e);
    }

    @Test
    public void test2(){
        Optional<Employee> op = Optional.empty();
        System.out.println(op.get());
    }

    @Test
    public void test3(){
        //Optional<Employee> op = Optional.ofNullable(new Employee());
        Optional<Employee> op = Optional.ofNullable(null);
        System.out.println(op.get());
    }

    @Test
    public void test4(){
        Optional<Employee> op = Optional.ofNullable(null);
        if(op.isPresent()){
            System.out.println(op.get());
        }
    }

    @Test
    public void test5(){
        Optional<Employee> op = Optional.ofNullable(null);
        Employee emp = op.orElse(new Employee("zhangsan",18));
        System.out.println(emp);
    }

    @Test
    public void test6(){
        Optional<Employee> op = Optional.ofNullable(null);
        Employee emp = op.orElseGet(Employee::new);
        System.out.println(emp);
    }

    @Test
    public void test7(){
        Optional<Employee> op = Optional.ofNullable(new Employee("张三",18,888.8,Employee.Status.FREE));
        Optional<String> opt = op.map(Employee::getName);
        System.out.println(opt.get());
    }

    @Test
    public void test8(){
        Optional<Employee> op = Optional.ofNullable(new Employee("张三",18,888.8,Employee.Status.FREE));

        Optional<String> opt =  op.flatMap(employee -> Optional.of(employee.getName()));
        System.out.println(opt.get());
    }
}
